<template>
    <common-page title="注册账号">
        <el-steps :active="stepActive" simple finish-status="success">
            <el-step title="基础信息"/>
            <el-step title="账户信息"/>
            <el-step title="完成注册"/>
        </el-steps>
        <el-form v-if="stepActive == 0" ref="stepForm_one" :model="form" :rules="rules" :label-width="120">
            <el-form-item label="头像" prop="avatar">
                <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload">
                    <img v-if="form.avatar" :src="formAvatar(form.avatar)" class="avatar" alt="">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
                <el-input v-model="form.nickname" placeholder="请输入昵称"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="form.gender">
                    <el-radio v-for="state in genderOptions" :key="state.key" :value="state.key">
                        {{ state.label }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="真实姓名" prop="realname">
                <el-input v-model="form.realname" placeholder="请输入真实姓名"/>
            </el-form-item>
            <el-form-item label="手机号码" prop="mobile">
                <el-input v-model="form.mobile" placeholder="请输入手机号码"/>
            </el-form-item>
            <el-form-item label="身份证号" prop="identity">
                <el-input v-model="form.identity" placeholder="请输入身份证号"/>
            </el-form-item>
        </el-form>
        <el-form v-if="stepActive == 1" ref="stepForm_two" :model="form" :rules="rules" :label-width="120">
            <el-form-item label="邮箱地址" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱地址"></el-input>
                <div class="el-form-item-msg">邮箱地址将作为登录时的唯一凭证</div>
            </el-form-item>
            <el-form-item label="登录密码" prop="password">
                <el-input v-model="form.password" type="password" show-password placeholder="请输入登录密码"></el-input>
                <fc-password-strength v-model="form.password"></fc-password-strength>
                <div class="el-form-item-msg">请输入包含英文、数字的8位以上密码</div>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirm">
                <el-input v-model="form.confirm" type="password" show-password
                          placeholder="请再一次输入登录密码"></el-input>
            </el-form-item>
            <el-form-item label="邮箱验证码" prop="captcha">
                <div class="yzm">
                    <el-input v-model="form.captcha" placeholder="请输入邮箱验证码"></el-input>
                    <el-button @click="getCaptcha(stepForm_two)" :disabled="disabled">发送验证码<span v-if="disabled">
                            ({{ countdown }})</span></el-button>
                </div>
            </el-form-item>

            <el-form-item label="" prop="agree">
                <el-checkbox v-model="form.agree" label="">已阅读并同意</el-checkbox>
                <span class="link"
                      @click="showAgree = true">《服务协议》</span>
            </el-form-item>
        </el-form>

        <div v-if="stepActive >= 2">
            <el-result icon="success" title="注册成功" sub-title="可以使用账号登录、验证码或微信公众号登录系统">
                <template #extra>
                    <el-button type="primary" @click="goLogin">前去登录</el-button>
                </template>
            </el-result>
        </div>
        <el-form style="text-align: center;">
            <el-button v-if="stepActive > 0 && stepActive < 2" @click="pre">上一步</el-button>
            <el-button v-if="stepActive < 1" type="primary" @click="next(stepForm_one)">下一步</el-button>
            <el-button v-if="stepActive == 1" type="primary" @click="save(stepForm_two)">提交</el-button>
        </el-form>
        <el-dialog :top="'8vh'" v-model="showAgree" title="服务协议" :width="800" destroy-on-close>
            <agreement></agreement>
            <template #footer>
                <el-button @click="showAgree = false">取消</el-button>
                <el-button type="primary" @click="showAgree = false; form.agree = true;">我已阅读并同意</el-button>
            </template>
        </el-dialog>
    </common-page>
</template>

<script setup lang="ts">
import commonPage from './components/commonPage.vue'
import {ElMessage, type FormInstance, FormRules} from 'element-plus'
import {reactive, ref} from 'vue';
import router from '@/router';
import {formAvatar} from "@/utils/user.ts";
import {fileUpload} from "@/utils/upload.ts";
import agreement from "./agreement.vue";
import {sendEmailCaptcha} from "@/api/modules/guest.ts";
import {RegisterRequestModel} from "@/models/authModel.ts";
import {registerApi} from "@/api/modules/auth.ts";

const disabled = ref(false);
const countdown = ref(60);

const genderOptions = reactive([
    {key: 'HIDE', label: '未知'},
    {key: 'MAN', label: '男'},
    {key: 'WOMAN', label: '女'}
]);

const stepActive = ref(0);
const showAgree = ref(false);
const form = reactive<RegisterRequestModel>({
    avatar: "/img/logo.png",
    nickname: "",
    gender: genderOptions[0].key,
    realname: "",
    mobile: "",
    identity: "",
    email: "",
    password: "",
    confirm: "",
    captcha: "",
    agree: false,
});
const rules = reactive<FormRules<RegisterRequestModel>>({
    avatar: [
        {required: true, message: '请选择头像'}
    ],
    nickname: [
        {required: true, message: '请输入昵称'}
    ],
    gender: [
        {required: true, message: '请输入性别'}
    ],
    realname: [
        {required: true, message: '请输入真实姓名'}
    ],
    mobile: [
        {required: true, message: '请输入联系方式'}
    ],
    identity: [
        {required: true, message: '请输入身份证号码'}
    ],

    email: [
        {required: true, message: '请输入邮箱地址'},
    ],
    password: [
        {required: true, message: '请输入密码'}
    ],
    confirm: [
        {required: true, message: '请再次输入密码'},
        {
            validator: (_rule, value, callback) => {
                if (value !== form.password) {
                    callback(new Error('两次输入密码不一致'));
                } else {
                    callback();
                }
            }
        }
    ],
    captcha: [
        {required: true, message: '请输入验证码'}
    ],
    agree: [
        {
            validator: (_rule, value, callback) => {
                if (!value) {
                    callback(new Error('请阅读并同意协议'));
                } else {
                    callback();
                }
            }
        }
    ],
});

const stepForm_one = ref<FormInstance>();
const stepForm_two = ref<FormInstance>();

const pre = () => {
    stepActive.value -= 1;
};
const next = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid) => {
        if (!valid) return;
        stepActive.value += 1;
    });
};
const save = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate(async (valid) => {
        if (!valid) return;
        try {
            await registerApi(form);
            stepActive.value += 2;
        } catch (error) {
            console.log(error);
        }
    });
};
const goLogin = () => {
    router.replace({path: '/login'});
};
const beforeAvatarUpload = (file: File) => {
    const result = fileUpload(file);
    result.then(blob => {
        form.avatar = blob;
    }).catch(error => {
        ElMessage.error(error);
    });
    return false;
};
const getCaptcha = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validateField("email", async (valid) => {
        if (!valid) return;
        try {
            await sendEmailCaptcha({email: form.email});
            disabled.value = true;
            countdown.value = 60;
            const t = setInterval(() => {
                countdown.value -= 1;
                if (countdown.value < 1) {
                    clearInterval(t)
                    disabled.value = false;
                    countdown.value = 0;
                }
            }, 1000);
        } catch (error) {
            ElMessage.error("发送验证码失败，请重试！");
        }
    });
};
</script>

<style scoped>
.avatar-uploader ::v-deep(.el-upload) {
    width: 120px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
    cursor: pointer;
    overflow: hidden;
}

.avatar-uploader ::v-deep(.el-upload) .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
}

.avatar-uploader ::v-deep(.el-upload) .avatar {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
</style>
